#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on 2014-3-21, by junn
#

############################################################
##         Server 基础配置 
############################################################


import os
from celery.schedules import crontab
#import posixpath
#from settings import log_settings

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/etc/mysql/my.cnf',
        }, 
    }
}


### Redis 
# Note: ``LOCATION`` needs to be host:port:db_id
CACHES = {
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379:0',
        'OPTIONS': {
            'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {'max_connections': 100}
        },
    },
}


## Every write to the cache will also be written to the database, 
# Session reads only use the database if the data is not already in the cache.
# this setting depends on CACHES setup    
#SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"

# For this type session cache, Session data will be stored directly your cache, 
# and session data may not be persistent
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = 'default'


# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []


AUTH_USER_MODEL = 'users.User'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Shanghai'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-cn'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

############# 以下设置为相对路径

# 用户头像设置
USER_DEFAULT_AVATAR = 'user_avatar_default1.jpg'           
USER_AVATAR_DIR = {
    'original': 'img/avatar/originals',
    'thumb':    'img/avatar/thumbs'
}

IMG_DIR = {
    'original': 'img/originals',    #原图目录
    'thumb':    'img/thumbs',       #缩略图目录         
}

AUD_DIR = {
    'original': 'aud/originals',    #原声语音文件目录
    'scale':    'aud/scale',        #变声语音文件目录
}

DEFAULT_THUMB_SIZE = (400, 400)     #默认缩略图尺寸配置

AUD_FEEDBACK_DIR = 'aud/feedbacks'



# ADMIN_MEDIA_PREFIX = posixpath.join(STATIC_URL, "grappelli/")

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    
    ("nian", os.path.join(STATIC_ROOT, 'nian')),  # Just added for local debug env
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '0)7s+*yxa8ijrh3u7!y$^0#lv$kycl5!-hq0yp*wsx90kasdfa3dkjj'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = [
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    
    'core.middleware.GetTokenMiddleware',
#     'core.middleware.AuthedAppMiddleware',        # 验证授权客户端请求
]

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

TEMPLATE_CONTEXT_PROCESSORS = [
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.static",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    'django.core.context_processors.csrf',
    'django.contrib.messages.context_processors.messages',
     
     # nian
    #"core.context_processors.import_settings",
]

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    #"grappelli",            # grappelli, filebrower must before django.contrib.admin
    #"filebrowser",
    
    'django.contrib.admin',         #django admin
    "debug_toolbar",

    'rest_framework',
    'rest_framework.authtoken',   # for TokenAuthentication
    
    'djcelery',
    'django_crontab',

    'auth',
    'utils', 
    'users',
    'families',
    'posts',
    'regards',
    'feedbacks',
    'system',
    'packages',
    
    'runtests', 
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',                                
        'core.authentication.CustomAuthentication',
    )
}

FIXTURE_DIRS = [
    os.path.join(PROJECT_ROOT, "resources/fixtures"),
]

DATE_FORMAT = 'Y-m-d'
DATETIME_FORMAT = 'Y-m-d H:i:s'

CSRF_FAILURE_VIEW = 'core.views.csrf_failure'

SMS_CODE_EXPIRY = 10        #短信验证码有效时间, 单位:分钟
SMS_CODE_REQUIRED = True    #短信验证码开关变量


''' app包下载配置(fir.im, 为与前一版本兼容保留该配置) '''
QUERY_VERSION_URL = 'http://fir.im/api/v2/app/version/541a7131f880a6a814000087?token=dF0zexxxxxxI3Zfxxxxxxxxxxxxx'
ANDROID_DOWNLOAD_URL = 'http://fir.im/nian/install?type=android&token=dF0zeqBMxxxxxxxxx0w61fYxxxxxxxxxxxxxxxxx'

''' app包下载配置(采用七牛云存储) '''
PKG_DOWNLOAD_BASE_URL = 'http://dl.dondon.im'       #配置DNS CNAME到七牛云, 服务端不直接处理该URL请求
PKG_DOWNLOAD_URL = 'http://dondon.im/download'      #对外公开的下载地址, 由该地址重定向请求到真实下载地址

QINIU = {
     'access_key': 'xxxxxxx',
     'secret_key': 'xxxx-xxxxx',
       
     'bucket_name': 'dondon_1',
     'android_pkg_url': 'apks',
     'ios_pkg_url': 'ipas',               
}

# 手机验证码短信内容设定. 需与云片网站上短信模板严格设置一致
SMS_TEXT = {
    'signup': """【咚咚】验证码:{0}(注册), 10分钟内有效.""",
    'bind':   """【咚咚】验证码:{0}(绑定手机号), 10分钟内有效.""",
    'reset':  """【咚咚】验证码:{0}(重置密码), 10分钟内有效.""",
}

# 验证短信模板设定
SMS_TPL = {
    'signup': 3581001,  # 短信服务上的短信模板id
    'bind':   3581002,
    'reset':  3581003
}


# 添加家庭成员短信内容
SMS_CONTENT_UNSIGNEDUP = '''已将你添加到我的【咚咚】亲友里, 用手机号 {0} 和密码 {1} 就可登录. 如需下载安装请点击: %s''' % PKG_DOWNLOAD_URL
SMS_CONTENT = '已将你添加到我的【咚咚】亲友里, 登录【咚咚】了解我的动态并与我互动吧.'

# 注册, 添加用户并发送问候
REGARD_SMS = '''我在【咚咚】给你发送了问候, 用手机号 {0} 和密码 {1} 可登录查看. 如需下载安装【咚咚】请点击: %s''' % PKG_DOWNLOAD_URL

# 获取新动态条数线程睡眠时间(秒)
CUPT_SLEEP_INTERVAL = 30

## 家庭内允许的最大成员数
MAX_MEMBERS_COUNT = 32

## 问候发送线程, 用于保存线程对象变量
RS_THREAD = None


SYS_ADMIN = 81000029        # 系统消息发送预设的user_id
SYS_TIP_SENDER = 81000090   # 提醒发送预设的user_id

## following for celery settings
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/1'  
CELERY_RESULT_BACKEND = 'redis://localhost:6379/1'
# CELERY_IGNORE_RESULT = True

#from celery.schedules import crontab
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
    #定时查询出待发送问候
    "query_waiting_regards": {
        "task": "regards.tasks.query_waiting_regards",  #this need to set full path
        "schedule": timedelta(seconds=60),
        #"args": (16, 16)
     },
                       
    # 定时查询待触发的事件提醒                   
    "query_waiting_datetips": {
        "task": "regards.tasks.query_waiting_datetips",
        "schedule": timedelta(seconds=3*60), #3*60
     },                         
                       
    # 定时查询待推送的问候消息                   
    "push_new_messages": {
        "task": "regards.tasks.push_new_messages",
        "schedule": timedelta(seconds=15),
     },       
                       
    # 每隔一定小时将消息推送错误次数(pushed_err_count)清0
    "clear_pushed_err_count": {
        "task": "regards.tasks.clear_pushed_err_count",
        "schedule": timedelta(seconds=1*60*60),  #暂设置为2小时
        
        # Executes every Monday morning at 7:30 A.M 
        #'schedule': crontab(hour=7, minute=30, day_of_week=1),
        
     },    

    # 每天凌晨某时间点开始执行任务                   
    "incr_datetip_year": {
        "task": "regards.tasks.incr_datetip_year",
        "schedule": crontab(hour=3, minute=10), # Run at 03:10
     },                         

}
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"

# jpush settings
JPUSH = {
    'app_key':          'xxxxxxxxxx',
    'master_secret':    'xxxxxxxxxx',
}

IS_TEST_PKG = False    # 在admin后台进行新安装包版本更新时需要该参数, 以便安装包传到qiniu

try:
    from log_settings import *
except ImportError:
    pass